/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mangaviewer.servlet;

import com.mangaviewer.http.client.SearchHttpClient;
import com.mangaviewer.json.IOMangaJsonFile;
import com.mangaviewer.model.Manga;
import com.mangaviewer.util.SearchConstants;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author dorian
 */
@WebServlet(name = "FetchMangaList", urlPatterns = {"/fetchmangalist/*"})
public class FetchMangaListFromServer extends HttpServlet {

  private static final String EMPTY = "/empty";
  private static final String REDIRECT_TO_SEARCH_MANGA = "/redirecttosearchmanga";
  
  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    Logger.getLogger(FetchMangaListFromServer.class.getName()).log(Level.INFO, "RequestURI: " + request.getRequestURI());
    if (EMPTY.equals(request.getPathInfo())) {
      IOMangaJsonFile.write(new ArrayList<Manga>());
    } else {
      List<Manga> manga = SearchHttpClient.fetchMangaListFromServer();
      IOMangaJsonFile.write(manga);

      if (REDIRECT_TO_SEARCH_MANGA.equals(request.getPathInfo())) {
        String query = request.getParameter("q");
        if (query != null) {
          try {
            response.sendRedirect(SearchConstants.SEARCH_MANGA_URL + "?q=" + query);
          } catch (IOException ex) {
            Logger.getLogger(FetchMangaListFromServer.class.getName()).log(Level.SEVERE, "Could not redirect to /searchmanga", ex);
          }
        }
      } else {
        int mangaCount = manga.size();
        List<String> mangaTitles = new ArrayList<String>();
        for (Iterator<Manga> it = manga.iterator(); it.hasNext();) {
          Manga item = it.next();
          mangaTitles.add(item.getT());
        }

        request.setAttribute("mangaCount", mangaCount);
        request.setAttribute("mangaTitles", mangaTitles);

        this.getServletContext().getRequestDispatcher("/WEB-INF/fetchmangalistfromserver.jsp").forward(request, response);
      }
    }
  }

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>
}
